<template>
  <div class="cont">
    <el-form
      :model="ruleForm"
      status-icon
      :rules="rules"
      ref="ruleForm"
      class="demo-ruleForm"
    >
      <h1>新增管理员</h1>
      <el-form-item prop="name">
        <el-input
          type="text"
          v-model="ruleForm.name"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >提交</el-button
        >
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { addAdmin } from '@/api/User'

export default {
  name: 'AddAdmin',
  data() {
    var checkAdmin = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('用户名不能为空'))
      } else {
        callback()
      }
    }
    return {
      ruleForm: {
        name: ''
      },
      rules: {
        name: [{ validator: checkAdmin, trigger: 'blur' }]
      }
    }
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          addAdmin(this.$store.state.token, this.ruleForm.name).then((res) => {
            console.log(res)
            if (res.data.status == 'success') {
              this.$message({
                message: res.data.msg,
                type: 'success'
              })
              this.$alert(
                `
                <div><i>用户名:  ${res.data.username}</i> </div>
                <div><i>密码:  ${res.data.password}</i> </div>
                `,
                {
                  dangerouslyUseHTMLString: true
                }
              )
            } else {
              this.$message.error('新增失败')
            }
          })
        } else {
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>

<style scoped>
.cont {
  width: 100%;
  height: 700px;
  background-color: white;
  margin: 30px 0;
  display: flex;
  justify-content: center;
  text-align: center;
}

.cont h1 {
  font-size: 60px;
  margin-top: 200px;
  color: rgb(133, 133, 133);
}
</style>